﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;

namespace M
{
    public class FileM
    {
        public static string Read(string relatePath)
        {
            relatePath = relatePath.Replace("\\", "/");
            if (!relatePath.StartsWith("~"))
            {
                if (!relatePath.StartsWith("/")) relatePath = "/" + relatePath;
                if (!relatePath.StartsWith("~")) relatePath = "~" + relatePath;
            }
            return File.ReadAllText(HttpContext.Current.Server.MapPath(relatePath));
        }

        public static void Write(string path, string content)
        {
            string fileName = path.Split(new char[] {'/','\\' }).Last();
            string dir = path.Remove(path.Length - fileName.Length);
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            File.WriteAllText(path, content);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="FileUpload1"></param>
        /// <param name="relateDir">Ví dụ "/Image/"</param>
        /// <returns></returns>
        public static string UploadAndReturnURL(FileUpload FileUpload1, string relateDir)
        {
            if (!FileUpload1.HasFile) return "";
            FileUpload1.SaveAs(HttpContext.Current.Server.MapPath(relateDir) + FileUpload1.FileName);
            return relateDir + FileUpload1.FileName;
        }

        public static void Delete(string relatePath)
        {
            if (!relatePath.StartsWith("/")) relatePath = "/" + relatePath;
            if (!relatePath.StartsWith("~")) relatePath = "~" + relatePath;
            File.Delete(HttpContext.Current.Server.MapPath(relatePath));
        }
    }
}